package controllers;

import helpers.FileHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.CurrentDomain;

import crawlers.WebpagetestBreakdown;
import crawlers.WebpagetestCrawler;
import crawlers.WebpagetestResult;
import debugs.DomainDebug;

import entities.Domain;

import models.DomainModel;

public class CheckServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		String update = (String) request.getParameter("u");
		//Check name empty
		if (name == null || name.isEmpty()) {
			response.sendRedirect("/");
			return ;
		}
		
		name = UrlHelper.getMainDomain(name);
		
		//Check is domain
		if (!UrlHelper.checkDomain(name)) {
			response.sendRedirect("/");
			return ;
		}
		
		Domain domain = FileHelper.getDomainByFileName(name);
		
		if (domain == null) {
			domain = new Domain();
			domain.setDomain(name);
			domain.setProcessing(true);
			
		}
		
		if (domain.isProcessing()) {
			response.sendRedirect("/step/" + name);
			return;
		}
		
		CurrentDomain.insert(name);
		
		request.setAttribute("domain", domain);
		request.setAttribute("title", name + " - Speed test result");
		request.setAttribute("keywords", name + ", speedtestlab, speed test, content breakdown, wallterfal page, test performance, speed performance site");
		request.setAttribute("description", name + " - Result test with content breakdown site .");
		try {
			request.getRequestDispatcher("/pages/pagetest.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
